﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Practices.Unity;
using SharedLib.WinFormMVCFramework;
using TracyGUI.View;
using Tracy.DataModel;
using Tracy;
using Tracy.Messages;
using Tracy.Handlers;
using TracyGUI.Model;
using SharedLib.MessageFramework.Messages;
using System.IO;

namespace TracyGUI.Controller
{
    class DownloadCheckListViewController : ControllerBase<IDownloadCheckListView>, IController<IDownloadCheckListView>
    {

        protected override IDownloadCheckListView ResolveView()
        {
            return Tracy.TracyFacade.Instance.DIContainer.Resolve<IDownloadCheckListView>();
        }

        public DownloadCheckListViewController()
        {
            View.ResourceSelectionConfirmed += new EventHandler<SharedLib.GenericEventArgs<List<Tracy.DataModel.Resource>>>(View_ResourceSelectionConfirmed);
            StartDownloadHandler.ResourceSentToDownloader += new EventHandler<SharedLib.GenericEventArgs<Resource>>(StartDownloadHandler_ResourceSentToDownloader);
            AssignMediaFileHandler.MediaFileAssigned += new EventHandler<SharedLib.GenericEventArgs<IList<MediaFile>>>(AssignMediaFileHandler_MediaFileAssigned);
        }

        #region View Events
        void View_ResourceSelectionConfirmed(object sender, SharedLib.GenericEventArgs<List<Tracy.DataModel.Resource>> e)
        {
            TracyFacade.Instance.ExceptionManager.Process(() =>
            {
                foreach (Resource res in e.Data)
                {
                    SendResourceToDownload(this, res);
                }
            }, "UI Policy");
        }
        #endregion

        public static void SendResourceToDownload(object sender, Resource res)
        {
            if (res != null && res.Entry != null && Tracy.TracyFacade.Instance.EntryProvider.GetItemByID(res.Entry.ID) != null)
            {
                //Assign media file
                TaskMessage msgAssignMediaFile = new TaskMessage(sender, typeof(AssignMediaFileHandler), res, null);
                msgAssignMediaFile.CallBack = new SharedLib.MessageFramework.MessageCallback((msgA) =>
                {
                    if (msgA != null && msgA.Exception == null)
                    {
                        //Start downloader if media file assigment completed
                        TaskMessage msgStartDownloadHandler = new TaskMessage(sender, typeof(StartDownloadHandler), res, null);
                        msgStartDownloadHandler.CallBack = new SharedLib.MessageFramework.MessageCallback((msgS) =>
                        {
                            if (msgS != null && msgS.Exception == null)
                            {
                                //Notify user
                                NotificationManager.Notify(sender, TracyFacade.Instance.LanguageManager.GetText("Notification_ResourceSent_Title"), res.Title);

                                //Remove temp torrent file if exists
                                if (res.Attributes.ContainsKey("local-torrent-file"))
                                {
                                    string tempTorrentFile = res.Attributes["local-torrent-file"];
                                    if (File.Exists(tempTorrentFile))
                                    {
                                        File.SetAttributes(tempTorrentFile, FileAttributes.Normal);
                                        File.Delete(tempTorrentFile);
                                    }
                                }
                            }
                        });

                        TracyFacade.Instance.MessageDispatcher.EnqueueMessage(msgStartDownloadHandler);
                    }
                });

                TracyFacade.Instance.MessageDispatcher.EnqueueMessage(msgAssignMediaFile);
            }
        }

        public void ProcessResource(Resource res, bool autoMode)
        {
            //Send to download
            if (autoMode)
            {
                SendResourceToDownload(this, res);
            }
            else
            {
                View.ShowResourceForDownload(res);
            }
        }

        void StartDownloadHandler_ResourceSentToDownloader(object sender, SharedLib.GenericEventArgs<Resource> e)
        {
            if (e.Data.Status != "Sent")
            {
                e.Data.Status = "Sent";
                TracyFacade.Instance.ResourceProvider.UpdateItem(e.Data);
            }
        }

        void AssignMediaFileHandler_MediaFileAssigned(object sender, SharedLib.GenericEventArgs<IList<MediaFile>> e)
        {
            TracyFacade.Instance.MediaFileProvider.AddItems(e.Data);
        }
    }
}
